package com.mytools.tool.utils;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import android.util.Base64;
import android.util.Log;

/***
 * 对字符串 加密，解析
 * @author Lijinpeng
 */
public class StringUtil {

	public static String mobileUtil(String time) {
		String t = time;
		if (time.length() == 11) {
			t = time.substring(0, 3) + "*****" + time.substring(7, 11);
		}
		return t;
	}

	// 去除所有空格
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}

	//判断是否为空
	public static boolean isNull(String s) {
		if (null == s || s.equals("") || s.equalsIgnoreCase("null")) {
			return true;
		}
		return false;
	}
	/**
	 * email格式验证
	 * 
	 * @param string
	 * @return 验证通过返回true
	 */
	public static boolean checkEmail(String email) {
		Pattern pattern = Pattern
				.compile("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
		Matcher matcher = pattern.matcher(email);
		return matcher.matches();

	}
	/**
	 * 判断邮编
	 * @param paramString
	 * @return
	 */
	public static boolean isZipNO(String zipString){
		String str = "^[1-9][0-9]{5}$";
		return Pattern.compile(str).matcher(zipString).matches();
	}
	/**
	 * 手机号验证
	 * 
	 * @param string
	 * @return 验证通过返回true
	 */
	public static boolean isMobile(String str) {
		boolean b = false;
		if(isNull(str))return b;
		Pattern p = null;
		Matcher m = null;
		p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}
	/**
	 * 密码加密
	 * 
	 * @param src
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encryptThreeDESECB(String src, String key)
			throws Exception {
		DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
		SecretKey securekey = keyFactory.generateSecret(dks);

		Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, securekey);
		byte[] b = cipher.doFinal(src.getBytes());

		Log.e("code", Base64.encodeToString(b, Base64.DEFAULT)
				.replaceAll("\r", "").replaceAll("\n", ""));
		return Base64.encodeToString(b, Base64.DEFAULT)
				.replaceAll("\r", "").replaceAll("\n", "");
	}

	/***
	 * 参数加密
	 * 
	 * @param paramValues
	 * @param secret
	 * @return 加密sign
	 */
	public static String sign(Map<String, String> paramValues, String secret) {
		StringBuilder sign = new StringBuilder();
		try {
			byte[] sha1Digest = null;
			StringBuilder sb = new StringBuilder();
			List<String> paramNames = new ArrayList<String>(paramValues.size());
			paramNames.addAll(paramValues.keySet());
			Collections.sort(paramNames);
			sb.append(secret);
			for (String paramName : paramNames) {
				sb.append(paramName).append(paramValues.get(paramName));
			}
			sb.append(secret);
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			sha1Digest = md.digest(sb.toString().getBytes("UTF-8"));
			for (int i = 0; i < sha1Digest.length; i++) {
				String hex = Integer.toHexString(sha1Digest[i] & 0xFF);
				if (hex.length() == 1) {
					sign.append("0");
				}
				sign.append(hex.toUpperCase());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		Log.e("sign", sign.toString());
		return sign.toString();
	}

    /**将单位为分 转化为 单位为元（保留两位小数）*/
    public static String priceShow(int price) {
        double d = price / 100.0;
        String strPrice = String.format("%.2f", d);
        return strPrice;
    }
    
    /**将单位为分 转化为 单位为元（保留两位小数）*/
    public static String priceShow2(double price) {
    	double remainder = price%100;
        double d = price / 100.0;
        if(remainder==0){return String.format("%.0f", d);}
        else{return String.format("%.2f", d);}
    }
    
    public static String priceShow3(double price) {
    	int price_o = (int) (price*100);
    	double remainder = price_o%100;
        double d = price_o / 100.0;
        if(remainder==0){return String.format("%.0f", d);}
        else{return String.format("%.2f", d);}
    }
	
	public static String getMoneyString(long money){
		return String.format("%.2f", money/100f);

	}
	
	//万分转千分
    public static String rateShow(int rate) {
        double d = rate / 10.00;
        String strPrice = String.format("%.1f", d);
        return strPrice;
    }
    public static String rateShow(String rate) {
        return rateShow(Integer.parseInt(rate));
    }
	
//	public static String getBigImage(String url){
//		return MessageFormat.format(Config.POS_PIC_URL, url);
//	}
//	public static String getImage(String url){
//		return MessageFormat.format(Config.FILE_URL, url);
//	}
	public static String replaceNum(String num){
		if(num==null||"".equals(num)||num.length()<8){
			return num;
		}
		int length=num.length();
		String start=num.substring(0,length-8);
		String end=num.substring(length-4, length);
		
		return start+"****"+end;
	}
	public static String replaceName(String num){
		if(num==null||"".equals(num)||num.length()<2){
			return num;
		}
		int length=num.length();
		String start=num.substring(0,length-2);
		String end=num.substring(length-1, length);
		
		return start+"*"+end;
	}
	
	public static String getSubLimitString(String in, int size){
		String out = "";
		if(isNull(in))return "";
    	int length = in.length();
    	if(length>size){
    		out = in.substring(0, size)+"...";
    	}
    	else {out = in;}
    	return out;
	}
	
	/** 字符串转换unicode */
	public static String string2Unicode(String string) {
	    StringBuffer unicode = new StringBuffer();
	    for (int i = 0; i < string.length(); i++) {
	        // 取出每一个字符
	        char c = string.charAt(i);
	        // 转换为unicode
	        unicode.append("\\u" + Integer.toHexString(c));
	    }
	    return unicode.toString();
	}
	
	/** unicode 转字符串 */
	public static String unicode2String(String unicode) {
	    StringBuffer string = new StringBuffer();
	    String[] hex = unicode.split("\\\\u");
	    for (int i = 1; i < hex.length; i++) {
	        // 转换出每一个代码点
	        int data = Integer.parseInt(hex[i], 16);
	        // 追加成string
	        string.append((char) data);
	    }
	    return string.toString();
	}
	
    public static ArrayList<String> getSortAsc(ArrayList<String> a){
        String temp = "";
        int i;
        for(i=0;i<a.size();i++){
            for(int j=a.size()-1;j>i;j--){
                if(a.get(j).compareTo(a.get(j-1))<0){
                    temp=a.get(j);
                    a.set(j, a.get(j-1));
                    a.set(j-1, temp);
                }
            }
        }
        return a;
    }
    
	public static String createRandomStr(String randomChars, int length) {
	int size = randomChars.length();
	StringBuffer buffer = new StringBuffer();
	for (int i = 0; i < length; i++) {
		int random = new Random().nextInt(size);
		buffer.append(randomChars.charAt(random));
	}
	return buffer.toString();
}
	
}
